#include "widget.h"
#include "ui_widget.h"

#include <QTcpSocket>
#include "mythread.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    myServer = new QTcpServer;

    myServer->listen(QHostAddress::AnyIPv4, 8000);

    connect(myServer, &QTcpServer::newConnection, this, &Widget::handlerTcpConnect);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::handlerTcpConnect()
{
    QTcpSocket *s = myServer->nextPendingConnection();
    ui->ip->setText(s->peerAddress().toString());
    ui->port->setText(QString::number(s->peerPort()));
//    connect(s, &QTcpSocket::readyRead, this, &Widget::handleRecv);

    // start new thread handle connect
    MyThread *th = new MyThread(s);
    // connect signal and solt of define self
    connect(th, &MyThread::recvClientData, this, &Widget::handleThreadRecv);
    th->start();

}

void Widget::handleRecv()
{
    QTcpSocket *s = (QTcpSocket *)sender();
    ui->recv->setText(QString(s->readAll()));
}

void Widget::handleThreadRecv(QString data)
{
    ui->recv->setText(data);
}

